<template>
  <el-dropdown @command="handleLanguageChange" class="language-switcher">
    <span class="el-dropdown-link">
      <el-icon><Globe /></el-icon>
      {{ currentLanguageLabel }}
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="zh" :class="{ active: locale === 'zh' }">
          中文
        </el-dropdown-item>
        <el-dropdown-item command="en" :class="{ active: locale === 'en' }">
          English
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { ArrowDown, Globe } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const { locale, t } = useI18n()

const currentLanguageLabel = computed(() => {
  return locale.value === 'zh' ? '中文' : 'English'
})

const handleLanguageChange = (lang) => {
  if (lang !== locale.value) {
    locale.value = lang
    localStorage.setItem('language', lang)
    ElMessage.success(t('languageChanged'))
  }
}
</script>

<style scoped>
.language-switcher {
  margin-right: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: white;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.el-dropdown-link:hover {
  color: var(--el-color-primary);
}

.active {
  color: var(--el-color-primary);
  font-weight: bold;
}
</style>